import QtQuick 2.0
import "./Custom"

Unit {
    id: monster
    width: body.width
    height: body.height

    property var array: new Array

    Component.onCompleted:
    {
        moveSpeed = 1
        _MAX_HEALTHY = healthy = 1
        lifeColor = Qt.rgba(1,0,0,1)
    }

    onDie:
    {
        // die
        deleteMonster(iid)
    }

    onByHit: {
        // 闪
        animFlash.restart()
    }

    property var _ROLES: [
        "qrc:/images/monster1.png",
        "qrc:/images/monster1.png",
        "qrc:/images/monster1.png",
    ]

    property var gPlayer

    function setRole(v)
    {
        body.source = _ROLES[v]
    }

    function update()
    {
        var player = getPlayerObj()
        gPlayer = player

        // 转向
        if(player.x > monster.x)
        {
            body.mirror = true
        }
        else{
            body.mirror = false
        }

        var r = checkCollision(monster, player)

        if(r){
//            timer.start()
            gPlayer.hitSelf(monster.damage)
            // 后退一下, 让玩家能跑开
            if(monster.x < player.x )
            {
                monster.x -= 10
            }
            else if(monster.x > player.x)
            {
                monster.x += 10
            }
            if(monster.y < player.y )
            {
                monster.y -= 10
            }
            else if(monster.y > player.y)
            {
                monster.y += 10
            }
        }
        else{
//            timer.stop()
        }

        // 移动
        var center = Qt.point(monster.x+monster.width/2, monster.y+monster.height/2)
        var radian = Math.atan2(player.y - center.y, player.x - center.x)
        monster.x += Math.cos(radian) * moveSpeed
        monster.y += Math.sin(radian) * moveSpeed
    }

    Timer{
        id: timer
        interval: 1000
        repeat: true
        triggeredOnStart: true
        onTriggered: {
            gPlayer.hitSelf(monster.damage)
        }
    }

    Image {
        id: imgShadown
        source: "qrc:/images/shadown.png"
        anchors.horizontalCenter: parent.horizontalCenter
        y: body.y + body.height - height/2
    }
    Image{
        id: body
        mirror: false
    }

    SequentialAnimation{
        id: animFlash
        PropertyAnimation{target: body; property: "opacity"; from: 1; to: 0.5; duration: 200; }
        PropertyAnimation{target: body; property: "opacity"; to: 1; duration: 200; }
    }
}
